﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Core.Battle
{
    public class AbilitySummoner
    {
        private const int MAX_ELEMENT = 3;

        private IEntity player;

        public Element.Kind[] Elements { get; }

        public Action OnElementNotReady { get; set; }

        public AbilitySummoner(IEntity player)
        {
            this.player = player;
            Elements = new Element.Kind[MAX_ELEMENT];
            for (var i = 0; i < MAX_ELEMENT; i++)
            {
                Elements[i] = Element.Kind.Void;
            }    
        }

        public void PushElement(Element.Kind element)
        {
            for (var i = MAX_ELEMENT - 1; i >= 1; i--)
            {
                Elements[i] = Elements[i - 1];
            }
            Elements[0] = element;
        }

        // If current slot fits the condition, return a specific ability, or else return null
        public AbilityDef TrySummon()
        {
            // Count the frequency each element shows.
            uint cntElements = 0;
            foreach (var element in Elements)
            {
                if (element == Element.Kind.Void)
                {
                    OnElementNotReady();
                    return null;
                }

                // Uses bits to count.
                // Format:
                // cntElements: 0b  01   01     01
                //                  AIR  GRASS  WATER
                cntElements += Element.ELEMENT_BITS[(int)element];
            }

            if (Abilities.Get(cntElements) is AbilityDef def)
            {
                return def;
            }
            else
            {
                return null;
            }
        }
    }
}
